package com.lesama.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadTest4 {
    public static void main(String[] args) {
        SellTicketsTask4 task1 = new SellTicketsTask4();

        Thread t1 = new Thread(task1, "线程1");
        Thread t2 = new Thread(task1, "线程2");
        Thread t3 = new Thread(task1, "线程3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class SellTicketsTask4 implements Runnable {

    private int tickets = 10000;
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while(true) {
            try {
                lock.lock();
                if(tickets == 0) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "售出了第" + tickets + "张票");
                tickets--;
            } finally {
                lock.unlock();
            }
        }
    }
}
